﻿ui = qt.load_ui("people_login_info.ui")
ui:show()

qt.connect(ui.searchButton, "clicked",
	function()
		last_name = ui.lastName.text
		first_name = ui.firstName.text
		middle_name = ui.middleName.text
		group = ui.group.text
		
		if last_name:len() == 0 and first_name:len() == 0 and middle_name:len() == 0 and group:len() == 0 then
			qtt.warning("Внимание", "Не введено необходимых данных")
			return
		end;
		
		query = "SELECT `id` FROM `people` WHERE 1"
		if last_name:len() > 0 then
			query = query .. " AND `last_name`='" .. last_name .. "'"
		end;
		if first_name:len() > 0 then
			query = query .. " AND `first_name`='" .. first_name .. "'"
		end;
		if middle_name:len() > 0 then
			query = query .. " AND `middle_name`='" .. middle_name .. "'"
		end;
		if group:len() > 0 then
			sql.exec("SELECT `id` FROM `groups` WHERE `name`='" .. group .. "'")
			if sql.next() == 1 then
				group = sql.value(0)
			else
				qtt.warning("Внимание", "Класс (группа) с именем " .. group .. " не найдена")
				return
			end;
			query = query .. " AND `group`='" .. group .. "'"
		end;
		
		sql.exec(query);
		if sql.next() == 1 then
			id = sql.value(0);
		else
			qtt.warning("Внимание", "По заданным данным, не найдено ни одного человека")
			return;
		end;
		if sql.next() == 1 then
			qtt.warning("Внимание", "По заданным данным, найдено более одного человека")
			return;
		end;
		print("id=" .. id)
		print(query)
		
		query = "SELECT `last_name`,`first_name`,`middle_name`,`groups`.`name`,DATE_FORMAT(`day_start`, '%H:%i:%s'),DATE_FORMAT(`day_end`,'%H:%i:%s') FROM `people` LEFT JOIN `groups` ON `people`.`group` = `groups`.`id` WHERE `people`.`id`='" .. id .. "'"
		sql.exec(query)
		sql.next()
		ui.lastName:setText(sql.value(0))
		ui.firstName:setText(sql.value(1))
		ui.middleName:setText(sql.value(2))
		ui.group:setText(sql.value(3))
		ui.dayStart:setText(sql.value(4))
		ui.dayEnd:setText(sql.value(5))
		
		
		query = "SELECT DATE_FORMAT(`date`, '%H:%i:%s') FROM `log` WHERE DATE(`date`)=DATE(NOW()) AND `type` IN ('login','logout') AND `people_id`='" .. id .."' ORDER BY `type` ASC"
		print(query)
		sql.exec(query)
		if sql.next() == 1 then
			start_time = sql.value(0)
		else
			start_time = "Не доступно"
		end;
		
		if sql.next() == 1 then
			end_time = sql.value(0)
		else
			end_time = "Не доступно"
		end;
		ui.login:setText(start_time)
		ui.logout:setText(end_time)
	end
);

qt.connect(ui.clearButton, "clicked",
	function()
		ui.lastName:clear()
		ui.firstName:clear()
		ui.middleName:clear()
		ui.group:clear()
		ui.dayStart:clear()
		ui.dayEnd:clear()
		ui.login:clear()
		ui.logout:clear()
	end
);